#include "StateEndless.h"
#include "game/WaveEndless.h"

#include <iostream>



namespace VectorTD
{
	StateEndless::StateEndless()
		: m_gameState(LOAD_MAP)
		, m_map(NULL)
		, m_waves()
		, m_activeWaves()
		, m_nextWave(0)
	{

	}

	StateEndless::~StateEndless()
	{
		if(m_map != NULL)
			delete m_map;
	}

	bool StateEndless::Update(double p_deltaMs)
	{
		switch(m_gameState)
		{
		case LOAD_MAP:
			{
				m_map = new Map("map_0.data");

				for(int i = 0 ; i < 1 ; i++)
				{
					m_waves.push_back(new WaveEndless(i, m_map));
				}
				m_gameState = PLAY;
			}
			break;
		case PLAY:
			if(m_activeWaves.empty() && m_nextWave < m_waves.size())
			{
				InsertUpdatable(m_waves[m_nextWave]);
				m_activeWaves.push_back(m_waves[m_nextWave++]);
			}
			else if(!m_activeWaves.empty())
			{
				for(std::vector<Wave*>::iterator it = m_activeWaves.begin() ; it != m_activeWaves.end() ; it++)
				{
					std::vector<Unit*>& creepToAdd = (*it)->GetUpdatedCreeps();

					while(!creepToAdd.empty())
					{
						Unit* unit = creepToAdd.back();

						// Randomise a starting position
						float randomStartPosition = unit->m_scaleMat[0][0] + static_cast<float>((1.0f - 2*unit->m_scaleMat[0][0]) * rand()/(RAND_MAX + 1.0));
						
						unit->Spawn(glm::vec2((m_map->m_path[0]->x + randomStartPosition) * m_map->GetSizeCell(), (m_map->m_path[0]->y + 0.5f) * m_map->GetSizeCell()));
						creepToAdd.pop_back();
					}
				}
			}
			break;
		case PAUSE:
			break;
		case NONE:
			//LOG("NONE %lf\n", p_deltaMs);
			break;
		default:
			break;
		}
		return true;
	}
}